package mongo

import (
	"code.google.com/p/cloud9lib/rest"

	"launchpad.net/mgo/bson"
	"launchpad.net/mgo"
	"log"
	"net/http"
)

var db *mgo.Database
var fs *mgo.GridFS
var session *mgo.Session

const dbname = "cloud9lib"

func Open(url string) {
	log.Println("connecting to MongoDB at " + url)

	var err error
	session, err = mgo.Dial(url)

	if err != nil {
		log.Fatal("could not create MongoDB session server: " + err.Error())
	}

	err = session.Ping()

	if err != nil {
		log.Fatal("could not connect to MongoDB sever: " + err.Error())
	}

	log.Println("connected.")

	db = session.DB(dbname)
	fs = db.GridFS("fs")
}

func DB() *mgo.Database {

	return db
}

func FS() *mgo.GridFS {

	return fs
}

func Close() {

	log.Println("closing connection to MongoDB")

	session.Close()
}

type mongoResource struct {
	mgo.Collection
}

func (res mongoResource) GET(w http.ResponseWriter, req *http.Request) {

	id := req.FormValue("id")

	if id != "" {

		var obj bson.M

		res.Collection.Find(bson.M{"_id": bson.ObjectId(id)}).One(&obj)

		rest.WriteObject(w, req, obj)
	} else {

		obj := bson.M{"results": "blah"}

		rest.WriteObject(w, req, obj)
	}
}

func (res mongoResource) POST(w http.ResponseWriter, req *http.Request) {
}

func (res mongoResource) PUT(w http.ResponseWriter, req *http.Request) {
}

func (res mongoResource) DELETE(w http.ResponseWriter, req *http.Request) {
}


